local utf8 = require("utf8")
require "import"
import "android.content.Context"
import "android.content.Intent"
import "java.util.Locale"

import "android.speech.SpeechRecognizer"
import "android.speech.RecognitionListener"
import "android.speech.RecognizerIntent"
import "java.util.Locale"
import "android.content.Intent"


function splitSentences(text)
    local sentences = {}
    for sentence in text:gmatch("[^.!?]+[.!?]*%s*") do
        local new_sentence = capitalize(sentence)
        table.insert(sentences, new_sentence)
    end
    text = table.concat(sentences, "")
    return text
end


function splitSentencesWithComa(text)
    local sentences = {}
    for sentence in text:gmatch("[^,]+,*%s*") do
        local new_sentence = lower(sentence)
        table.insert(sentences, new_sentence)
    end
    text = table.concat(sentences, "")
    return text
end


local UKRAINIAN_ALPHABET_UPPER = "АБВГҐДЕЄЖЗИІЇЙКЛМНОПРСТУФХЦЧШЩЬЮЯ"
local UKRAINIAN_ALPHABET_LOWER = "абвгґдеєжзиіїйклмнопрстуфхцчшщьюя"

function capitalize(str)
    local firstLetter = utf8.sub(str, 1, 1)
    local restOfText = str:sub(2)
    local index = utf8.find(UKRAINIAN_ALPHABET_LOWER, firstLetter, 1, true)
    if index then
        firstLetter =utf8.sub(UKRAINIAN_ALPHABET_UPPER, index, index)
    end
    local symbols = {firstLetter}
    for symbol in restOfText:gmatch(utf8.charpattern) do
        table.insert(symbols, symbol)
    end
    local result = table.concat(symbols)
    return result
end


function lower(str)
    local firstLetter = utf8.sub(str, 1, 1)
    local restOfText = str:sub(2)
    local index = utf8.find(UKRAINIAN_ALPHABET_UPPER, firstLetter, 1, true)
    if index then
        firstLetter =utf8.sub(UKRAINIAN_ALPHABET_LOWER, index, index)
    end
    local symbols = {firstLetter}
    for symbol in restOfText:gmatch(utf8.charpattern) do
        table.insert(symbols, symbol)
    end
    local result = table.concat(symbols)
    return result
end
function startListening()
    local substitutionTable = {
        ["chino"] = "Jieshuo"
    }

    local verbalizationDetected = false
    
    local speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this)
    local speechListener = RecognitionListener{
        onResults = function(results)
            data = results.getParcelableArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
            if data ~= nil and data.size() > 0 then
                -- Se ha detectado alguna verbalización
                verbalizationDetected = true
                local recognizedText = data.get(0)
                recognizedText = string.gsub(recognizedText, " кома ", ", ")
                recognizedText = string.gsub(recognizedText, " крапка", ".")
                recognizedText = string.gsub(recognizedText, " знак питання", "?")
                recognizedText = string.gsub(recognizedText, " знак оклику", "!")
                recognizedText = string.gsub(recognizedText, " права дужка", ")")
                recognizedText = string.gsub(recognizedText, " ліва дужка", "(")
                recognizedText = string.gsub(recognizedText, " двокрапка", ":")
                recognizedText = string.gsub(recognizedText, " переведення рядка ", "\n")
                recognizedText = splitSentences(recognizedText)
                recognizedText = splitSentencesWithComa(recognizedText)
                recognizedText = capitalize(recognizedText)
                service.setText(node,recognizedText)
                service.speak(recognizedText)
            end
            -- Si no se detectó ninguna verbalización en el primer intento, detener reconocimiento de voz
            if not verbalizationDetected then
                speechRecognizer.destroy()
                return false
            end
        end,
        onError = function()
            -- Ocurrió un error, detener reconocimiento de voz
            speechRecognizer.destroy()
            return false
        end
    }
    
    local recognizerIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault())
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName())
    speechRecognizer.startListening(recognizerIntent)
    speechRecognizer.setRecognitionListener(speechListener)
    
    return true
end
startListening()
return true